import moment from 'moment'

const Tools = {
  /**
   * 组装echarts数据格式
   * @param {array} resource 
   * @param {object} params 
   * @param {object} sortParams 排序规则
   */
  arrayToECharts(resource, params, sortParams) {
    let result = {
      seriesData: [],
      xAxisData: []
    }
    let seriesData = [];
    let xAxisData = [];
    try {
      const { seriesItems, xAxis, yAxis, ...other } = params
      if (seriesItems && resource && Array.isArray(resource) && Array.isArray(seriesItems)) {
        if (sortParams) {
          // asc 按升/ desc 降序
          const { sortField, orderBy } = sortParams
          switch (orderBy) {
            case 'asc':
              resource.sort((a, b) => a[sortField] - b[sortField])
              break;
            case 'desc':
              resource.sort((a, b) => b[sortField] - a[sortField])
              break;
          }
        }
        seriesItems.forEach((element, index) => {
          const { field, name, ...items } = element;
          let data = []
          resource.forEach(ele => {
            if(ele[field] || ele[field] === 0) data.push(ele[field])
          });
          seriesData[index] = items;
          Object.assign(seriesData[index], { data: data, name })
        })
        // 处理 xAxis，{ field: 'time', format: 'M月' }
        let { field: xField, format: xFormat } = xAxis;
        xField = xField ? xField : 'time';
        resource.forEach(ele => {
          let v = ele[xField];
          if(v || v === 0){
            if(xFormat) { v = moment(v).format(xFormat)}
            xAxisData.push(v)
          }          
        })
        Object.assign(result, { xAxisData: xAxisData }, { seriesData: seriesData })
      }
      if(yAxis) Object.assign(result, { yAxis })
      if (other) {
        Object.assign(result, other)
      }
    } catch (e) {
      console.error(e.message)
    }
    return result;
  },
  /**
   * 对象转URL，注意JSON.stringify()将对象转字符串
   * @param {*} obj 
   */
  objectToQueryString(obj) {
    let qstring = '', i = 0;
    for (let key in obj) {
      if (i > 0) qstring += "&";
      let value = obj[key]
      if (Array.isArray(value) || Object.prototype.toString.call(value) === "[object Object]") value = JSON.stringify(value);
      qstring += key + "=" + value;
      i++;
    }
    return qstring
  },
  /**
   * 功能：格式化饼状图数据
   * @param {array} resource 
   * @param {object} params，如： { name: '名称', field: [{name: '一', value: 1}]}
   */
  formatPieData(resource, params) {
    let result = {
      seriesData: []
    }
    try {
      const { field, ...other } = params;

      let seriesData = []
      if (resource && Array.isArray(resource) && field && Array.isArray(field)) {
        field.forEach(element => {
          let data = [];
          const { value, name } = element;
          resource.forEach(ele => {
            data.push({ value: ele[value], name: ele[name] })
          })
          seriesData.push({ data: data })
        })
        Object.assign(result, { seriesData: seriesData })
      }
      if (other) {
        Object.assign(result, other)
      }
    } catch (error) {
      console.error(error)
    }
    return result;
  },
  /**
   * 转换成echart数据
   * @param {*} resourceArr 
   * @param {*} params 
   * {
   *     yAxis: [{ name: '百万' }, { name: '公里' }], // yAxis单位
   *     xAxis: { filed: 'YEAR' },                   // xAxis值字段
   *     seriesItems: [
   *       { name: '供水人口总数', filed: 'GSRKZS', type: 'line', style: 'areaStyle' }, // 默认yAxis值
   *       { name: '管网长度', filed: 'GWCD', type: 'line', yAxisIndex: 1 }             // 双坐标 yAxisIndex
   *     ],
   *     color: ['50,177,108', '0,244,255']
   * }
   */
  formatSQLData(resourceArr, params){
    let result = {
      xAxisData: [],
      seriesData: []
    }
    if(params.seriesItems)  Object.assign(result, { seriesData: this.formatSQLSeriesData(resourceArr, params.seriesItems) })
    if(params.xAxis) Object.assign(result, { xAxisData: this.formatSQLxAxisData(resourceArr, params.xAxis) })
    if(params.yAxis) Object.assign(result, { yAxis: params.yAxis })
    return result;
  },
  /**
   * 
   * @param {*} resourceArr 
   * @param {*} itemsArr 
   * output { xAxisData: [], seriesData: []}
   */
  formatSQLSeriesData(resourceArr, itemsArr){
    let result = []
    try {
      if(Array.isArray(resourceArr) && resourceArr.length >0 && Array.isArray(itemsArr)){
        itemsArr.forEach((element, index) => {
          const { name, field } = element;
          let data = [];
          resourceArr.forEach(ele => {
            const { attributes } = ele;
            if (attributes && (attributes[field] || attributes[field] === 0)) { // 如果有attributes，众智
              data.push(attributes[field])
            }else{
              if(ele[field] || ele[field] === 0) data.push(ele[field])
            }
          })
          result.push({name, data })
          // 将其它配置项合并
          Object.assign(result[index], element)
        })
      }
    } catch (error) {
      console.error(error)
    }
    return result;
  },
  formatSQLxAxisData(resourceArr, params){
    let result = []
    try {
      if (Array.isArray(resourceArr)) {
        const { field, format, formatStr } = params;
        resourceArr.forEach(ele => {
          const { attributes } = ele;
          if(attributes){
            if(format){
              result.push(moment(attributes[field], formatStr).format(format))
            }else{
              result.push(attributes[field])
            }
          }else{
            if(format){
              if(ele[field]) result.push(moment(ele[field], formatStr).format(format))
            }else{
              if(ele[field]) result.push(ele[field])
            }
          }
        })
      }
    } catch (error) {
      console.error(error)
    }
    return result
  },
  formatEmpty(data, key){
    let result = '-'
    if(data && (data[key] || data[key] === 0)){
      result = data[key];
    }
    return result;
  },
  /**
   * 
   * @param {*} Str 
   * @param {*} exp 
   */
  getExpression(Str, exp){
    var result = false;
    var Str1 = this.getExpressionVal(Str)
    if((Str1 || Str1 === 0) && exp){
      result = eval(Str1 + exp)
    }
    return result;
  },
  /**
   * 从字符串中获取表达式的值
   * "<2.2" => 2.2
   */
  getExpressionVal(Str){
    var reg = />|<|=/g;
    var result = Str;
    if(reg.test(Str)) result = Str.replace(reg, '')
    return result * 1;
  },
  getExpressionRange(Str, exp){
    var reg = /-/g;
    var result = false;
    var Str1 = this.getExpressionVal(Str)
    if(reg.test(exp)){
      var arr = exp.split('-')
      if(arr.length === 2){
        const expression =  '(' + arr[0] +' >= ' + Str1 + ') || ('+ Str1 +' <= ' + arr[1] + ')'
        result = eval(expression)
      }
    }
    return result;
  },
  /**
   * 某一时间段，字段的累加统计
   * @param {Array} arr 
   * @param {String|array} fields 为数组且数组长度大于1,则：f[0] - f[1]；否则为 f[0] 或 f
   * @param {Array} timeRange 秒级时间戳
   */
  SumRange(arr, fields, timeRange, time = 'time', zoom = 1){
    let sum = 0;
    const [start, end] = timeRange;
    let flag = Array.isArray(fields) && fields.length > 1 ? true : false;

    if(Array.isArray(arr)){
      arr.forEach(ele => {
        // typeof为number则为时间戳
        if(!ele) return false; // forEach中 reture false跳出循环

        const Time = (typeof(ele[time]) === 'number') ? ele[time] : moment(moment(ele[time])).unix();
        if(Time >= start && Time <= end ){
          // 两个值
          if(flag){
            sum += (ele[fields[0]] - ele[fields[1]])/zoom
          }else{
            sum += Array.isArray(fields) ? ele[fields[0]]/zoom : ele[fields]/zoom;
          }
        }
      })
    }
    return sum;
  },
  SumRangeTotal(arr, timeRange, time = 'date'){
    let sum = 0;
    const [start, end] = timeRange;
    if(Array.isArray(arr)){
      arr.forEach(ele => {
        // typeof为number则为时间戳
        if(!ele) return false; // forEach中 reture false跳出循环
        const Time = (typeof(ele[time]) === 'number') ? ele[time] : moment(moment(ele[time])).unix();
        if(Time >= start && Time <= end ){
          sum++
        }
      })
    }
    return sum;
  },
  /**
   * forEach 统计
   * @param {*} arr 
   * @param {*} field 
   */
  SumForEach(arr, field){
    let sum = 0;
    if(Array.isArray(arr)){
      arr.forEach(ele => {
        sum += ele[field]
      })
    }
    return sum;
  },
  /**
   * 生成当年所用月分
   * @param {*} year 
   */
  getFullMonth(year){
    let result = [];
    for (let i = 1; i <= 12; i++) {
      const month = i < 10 ? `0${i}` : i;
      result.push(`${year}-${month}`);
    }
    return result;
  },
  /**
   * 处理客服热线
   * @param {*} obj 
   */
  statisticsFormat(obj, year, param = ['trend', 'rate1', 'rate2']){
    let result = []
    // mock data
    // obj = {
    //   trend: { data: [{time: '2019-10', value: 1}]},
    //   rate1: { data: [{time: '2019-10', value: 12}]},
    //   rate2: { data: [{time: '2019-10', value: 12}]},
    // }

    const yearArr = this.getFullMonth(year)
    yearArr.map(time=>{
      let val = '-';
      let rate1 = '-';
      let rate2 = '-';
      // 处理结果
      if(obj && obj['trend']){
        const trendData = obj['trend'].data;
        const rate1Data = obj['rate1'].data;
        const rate2Data = obj['rate2'].data;

        // 当月第一天和当月最后一天，时间戳（秒）
        const startTimestamp = moment(moment(time).startOf('month')).unix();
        const endTimestamp = moment(moment(time).endOf('month')).unix();
        trendData.forEach(ele => {
          const { time: eTime } = ele;
          const Time = moment(eTime).unix();
          if(Time >= startTimestamp && Time <= endTimestamp ){
            val = this.findObj(trendData, eTime)
            rate1 = this.findObj(rate1Data, eTime)
            rate2 = this.findObj(rate2Data, eTime)
          }
        })
      }
      result.push({ time, val, rate1, rate2})
    })
    return result;
  },
  findObj(data, exp, value = 'value', field = 'time'){
    let result = null;
    if(Array.isArray(data)){
      const obj = data.find(ele => {
        if(ele[field] === exp) return ele;
      })
      if(obj && obj[field]) result = obj[value];
    }
    return result;
  },
  // 供水量
  countSupplyWater(resourceObj, SupplyId = 'HD76_103_P1'){
    let result = 0 ;
    try {
        if(resourceObj && Array.isArray(resourceObj.Sensors)){
          const { Sensors } = resourceObj;
          const curSensors = Sensors.find(ele =>{
            if(ele['Id'] === SupplyId){
              return ele
            }
          })
          const { Vals } = curSensors;
          if(Array.isArray(Vals)){
            Vals.map(val => {
              const { Report } = val;
              result += Report['maxv'];
            })
          }
        }
    } catch (error) {
      console.error(error)
    }
    return result;
  },
  // 售水量
  countSellWater(resourceArr){
    let result = 0;
    if(Array.isArray(resourceArr)){
      resourceArr.map(ele => {
        result += ele['value'];
      })
    }
    return result;
  },
  // 已收水费
  countSumPay(resourceObj, field = 'depositItems', zoom = 10000){
    let result = 0;
    if(resourceObj && Array.isArray(resourceObj[field])){
      resourceObj[field].map(ele => {
        result += ele['value'];
      })
      result = result/zoom;
    }
    return result;
  },
  // 处理 columns
  columnsList(list, value, key='value'){
    let result;
    if(Array.isArray(list)){
      result = list.find(function(ele){
        if(ele[key] === value) return ele;
      })
    }
    return result;
  },
  // 统计异常
  countAlarm(resource, fields){
    let result = [];
    if(Array.isArray(resource) && Array.isArray(fields)){
      fields.map(name => {
        let value = 0;
        resource.map(e => {
          if (e['context'] === name) {
            value++;
          }
        })
        result.push({ name, value })
      })
    }
    return result;
  },
  // 瞬时压力
  countYL(resource){
    let result = [];
    if(Array.isArray(resource)){
      resource.map(ele => {
        const { y } = ele;
        if(y) result.push(y);
      })
    }
    return result[result.length-1]
  }
};
export default Tools